# Copyright 1999-2007 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

inherit eutils autotools flag-o-matic multilib

DESCRIPTION="Powerful Constructive Solid Geometry modeling system."
HOMEPAGE="http://brlcad.org/"
SRC_URI="mirror://sourceforge/${PN}/${P}.tar.bz2"

LICENSE="LGPL-2 BSD BDL"
SLOT="0"
KEYWORDS="~amd64 ~x86"
IUSE="debug"

DEPEND="media-libs/libpng
	sys-libs/zlib
	dev-tcltk/itcl
	dev-tcltk/itk
	dev-tcltk/blt
	dev-tcltk/iwidgets
	media-libs/urt"

RDEPEND="${DEPEND}"

brlcadprefix="/usr/brlcad"

src_unpack() {
	unpack ${A}
	cd "${S}"
	#epatch "${FILESDIR}"/brlcad-tcltk-man_install.patch
	# eautoreconf doesn't seem to work, run autogen.sh
	epatch ${FILESDIR}/usr-local.patch
	filter-ldflags "-Wl,--as-needed"
	#sh autogen.sh
}

src_compile() {
	cd "${S}"
	local myconf
	filter-ldflags "-Wl,--as-needed"
	myconf="${myconf} --prefix=${brlcadprefix} \
		--libdir=${brlcadprefix}/$(get_libdir) \
		--enable-optimized --enable-tcl-build --enable-tk-build \
		--enable-opennurbs-build=yes --with-pic \
		--datadir=/usr/share/brlcad
		--with-tag "
	use debug &&
		myconf="${myconf} --enable-debug" ||
		myconf="${myconf} --disable-debug --enable-optimized"

	econf $myconf || die "configure failed"
	emake || die "emake failed"
}


src_install() {
einfo install
for f0 in ${S}/src/other/tcl ${S}/src/other/tk;
	do 
	sed -i -e 's/\$(UNIX_DIR)\/installManPage \$(MAN_FLAGS) \$\$i/\[ ! -e \$(TOP_DIR)\/doc\/\$\$i \] || \$(UNIX_DIR)\/installManPage \$(MAN_FLAGS) \$(TOP_DIR)\/doc\/\$\$i/' ${f0}/unix/Makefile
	done
	
	emake DESTDIR="${D}" install || die "emake install failed"
	#fix broken symlink
	cd ${D}/${brlcadprefix}/$(get_libdir)
	rm librtserver.so
	ln -s librt.so.19.0.1 librtserver.so
einfo "setting up /etc/env.d/99brlcad"
	dodir /etc/env.d || die
	echo "PATH=${brlcadprefix}/bin" > "${D}"/etc/env.d/99brlcad || die
	echo "LDPATH=${brlcadprefix}/$(get_libdir)" >> "${D}"/etc/env.d/99brlcad || die
	echo "MANPATH=${brlcadprefix}/man" >> "${D}"/etc/env.d/99brlcad || die
	cd ${D}${brlcadprefix}
	echo "ITK_LIBRARY=${brlcadprefix}/$(find $(get_libdir) -maxdepth 1 -type d -name 'itk*' -print)" >> "${D}"/etc/env.d/99brlcad || die
	echo "ITCL_LIBRARY=${brlcadprefix}/$(find $(get_libdir) -maxdepth 1 -type d -name 'itcl*' -print)" >> "${D}"/etc/env.d/99brlcad || die
}

pkg_postinst() {
	einfo "The standard starting point for BRL-CAD is the mged"
	einfo "command.  Examples are available in ${brlcadprefix}/db."
	einfo "To run an example, try:"
	einfo "${brlcadprefix}/bin/mged ${brlcadprefix}/db/havoc.g"
	einfo "In the mged terminal window, type 'draw havoc' to see"
	einfo "the wireframe in the visualization window."
}
